
import { createStore } from 'vuex'
import cache from '@/common/cache'
import router from '@/router';
import config from '@/config/index'
function getKeep() {
  let keep = true
  if (cache('form.keep') === false || cache('form.keep') === true) keep = cache('form.keep')
  return keep
}
export default createStore({
  state() {
    let userInfo = cache.get('userInfo', 'system') || [];
    let menuList = cache.get('menuList', 'system') || [];
    let actionList = cache.get('actionList', 'system') || [];
    let store = {
      userInfo: userInfo || {},//用户信息
      menuReged: false,//菜单初始化路由已注册
      win: {
        width: window.innerWidth,
        height: window.innerHeight,
        resize: '',
      },//视口参数
      scrollTop: 0,//内容区域实时滚动距离
      lang: cache('Language', null, '_vuex') || 'CN',//语言
      config: JSON.parse(JSON.stringify(config)),
      RfTokenLoading: false,//刷新token中
      count: 0,//测试字段
      noticeCount: 0,//通知数量
      actionList: actionList,//操作日志
      menuList: menuList,//菜单列表

    }
    return store
  },
  getters: {
  },
  mutations: {
    // 保存基础字段信息
    saveData(state, params) {
      console.log(params.value)
      state[params.field] = params.value
      if (params.keep) {
        if (params.scope) {
          cache(params.field, params.value, params.scope)
        } else {
          cache(params.field, params.value, 'vuex')
        }
      }
    },
    menuReged(state, data) {
      state.menuReged = data || false;
    },//菜单路由初始化
    // 退出登录
    Logout(state, params) {
      cache.clean('userInfo', 'system')
      cache.clean('menuList', 'system')
      cache.clean('actionList', 'system')
      state.userInfo = {}
      state.menuList = []
      state.actionList = []
      state.menuReged = false
      // 清除labellist缓存
      cache.clean('route', '_adminRoute');
      cache.clean('routeActive', '_adminRouteActive');
    }
  },
  actions: {
    // 保存基础字段信息
    saveData(store, params) {
      store.commit('saveData', params);
    },
    menuReged(store, params) {
      store.commit('menuReged', params);
    },
    async Logout (store, params) {
      store.commit('Logout', null);
    },
    waitRfToken(store) {
      return new Promise((resolve, reject) => {
        let timer = ''
        let running = () => {
          let next = store.state.RfTokenLoading
          if (!next) {
            store.commit('saveData', getKeep() ? cache('userInfo', null, 'system') : cache.se('userInfo', null, 'system'))
            resolve(true)
            timer && clearInterval(timer)
          }
          return next
        }
        if (running()) timer = setInterval(running, 300)
      })
    },//请求等待刷新token完成
  },
  modules: {

  }
})
